package controllers

import (
	"app/models"
	beego "github.com/beego/beego/v2/server/web"
)

type OrderController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// 展示
func (c *OrderController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	err := models.DB.Model(&models.Order{}).Count(&count).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "总数据查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	offset := (page - 1) * size
	order := []models.Order{}
	err = models.DB.Offset(offset).Limit(size).Find(&order).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "展示成功",
			Data: order,
		}
		c.ServeJSON()
	}
}

// 添加
func (c *OrderController) Add() {
	app := c.GetString("app")
	name := c.GetString("name")
	Price, _ := c.GetFloat("price")
	number, _ := c.GetInt("number")
	money, _ := c.GetFloat("money")
	img := c.GetString("img")
	order := models.Order{
		App:    app,
		Name:   name,
		Price:  Price,
		Number: number,
		Money:  money,
		Img:    img,
	}
	err := models.DB.Create(&order).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "数据添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "数据添加成功",
			Data: order,
		}
		c.ServeJSON()

	}
}

// 删除
func (c *OrderController) Del() {
	id, _ := c.GetInt("id")

	err := models.DB.Delete(&models.Order{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "数据删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "数据删除成功",
			Data: id,
		}
		c.ServeJSON()
	}
}

// 文件上传
func (c *OrderController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "请上传文件",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	path := "static/img/" + header.Filename
	img := "127.0.0.1:8080/" + path
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonR{Code: 500,
			Msg:  "文件上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "文件上传成功",
			Data: img,
		}
		c.ServeJSON()
	}
}
